import requests.hooks
from flask import Flask, render_template, request, send_file, redirect, jsonify
from flask_cors import CORS
import plistlib
import base64
import uuid
import re
import os
app = Flask(__name__)
app.config['APPLICATION_ROOT'] = '/webclip'
CORS(app)
@app.route('/webclip/index')
def index():
    return render_template('index.html')

@app.route('/webclip/result')
def result():
    u = request.form.get('url')
    if u is None:
        return ""
    return render_template('result.html?path='+u)

@app.route('/webclip/down')
def down():
    u = request.args.get('name')
    if u is None:
        return "", 404
    pattern = r'^[\w-]+\.mobileconfig$'
    if not re.match(pattern, u):
        return "", 404
    
    file_path = os.path.join('output', u)

    try:
        return send_file(file_path, as_attachment=True)
    except FileNotFoundError:
        return "", 404

import requests
def generateQrcode(text):
    url = "https://cli.im/Apis/QrCode/saveStatic"

    # 请求体数据
    data = {
        "info": text,
        "content": text,
        "level": "M",
        "size": "85",
        "codetype": "qr",
        "type": "text",
        "is_anonymous": "1",
        "static_create_from": "10003",
        "code_small_tyupe": "text",
        "qrcodeconfig[size]": "85",
        "base64": "",
        "code_small_type": "text",
        "codeimg": "1"
    }

    # 请求头
    headers = {
        "Accept": "application/json, text/plain, */*",
        "Accept-Language": "zh-CN,zh-Hans;q=0.9",
        "Content-Type": "application/x-www-form-urlencoded",
        "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Safari/605.1.15",
        "Referer": "https://cli.im/text/other"
    }

    # 发送 POST 请求
    response = requests.post(url, data=data, headers=headers)
    
    data = response.json()
    if (data.get("status") != 1):
        return ""
    return data.get("data").get("codeimg_base64")

@app.route('/webclip/generate', methods=['POST'])
def generate():
    # 获取用户输入
    url = request.form.get('url')
    label = request.form.get('label')
    desc = request.form.get('desc')
    icon_file = request.files.get('icon')


    webClip = {
        'PayloadType': 'com.apple.webClip.managed',
        'PayloadVersion': 1,
        'PayloadIdentifier': f'com.example.webclip.{uuid.uuid4()}',
        'PayloadUUID': str(uuid.uuid4()),
        'PayloadDisplayName': label,
        'PayloadDescription': f'WebClip for {label}',
        'PayloadOrganization': 'WebClip Generator',
        'URL': url,
        'Label': label,
        'FullScreen': True,
        'IsRemovable': True,
        'Precomposed': True,
    }
    # 处理图标文件
    icon_data = b''
    if icon_file:
        icon_data = icon_file.read()
        webClip['Icon'] = icon_data


    # 生成 mobileconfig 文件
    mobileconfig = {
        'PayloadContent': [webClip],
        'PayloadDisplayName': label,
        'PayloadDescription':desc,
        'PayloadIdentifier': f'com.example.webclip.config.{uuid.uuid4()}',
        'PayloadRemovalDisallowed': False,
        'PayloadType': 'Configuration',
        'PayloadUUID': str(uuid.uuid4()),
        'PayloadVersion': 1,
    }

    # 保存为临时文件
    config_filename = f'{label}.mobileconfig'
    with open("output/"+config_filename, 'wb') as f:
        plistlib.dump(mobileconfig, f)

    qrcode_content = "{}://{}/webclip/down?name={}".format(request.scheme,request.host, config_filename)
    base64img = generateQrcode(qrcode_content)
    return jsonify({"code":200,"msg":"success", "data":{"url":qrcode_content, "img":base64img}})

if __name__ == '__main__':
    app.run(debug=False,host="0.0.0.0",port=7894)